package module.scene
{
	import code.consts.TypeConst;
	import code.utils.ServerIdUtil;
	
	import com.darwin.darwinBitmapEngine.core.Node;
	import com.darwin.darwinBitmapEngine.view.SceneView;
	import com.darwin.darwinDll.Dll;
	import com.darwin.darwinDll.core.DllItem;
	import com.darwin.darwinDll.core.ResKey;
	import com.darwin.darwinIsometric.core.IsoObject;
	import com.darwin.darwinIsometric.core.IsoPosition;
	import com.darwin.darwinIsometric.core.Point3D;
	import com.darwin.darwinIsometric.core.isoConst.IsoTryResult;
	import com.darwin.darwinIsometric.core.isoConst.IsoType;
	import com.darwin.darwinIsometric.events.IsoMouseEvent;
	import com.darwin.darwinIsometric.events.IsoWorldEvent;
	import com.darwin.darwinIsometric.pathfinding.AStar;
	import com.darwin.darwinIsometric.pathfinding.MapGrid;
	import com.darwin.darwinIsometric.pathfinding.expand.WalkManager;
	import com.darwin.darwinIsometric.pathfinding.expand.WalkManagerEvent;
	import com.darwin.darwinIsometric.utils.IsoUtils;
	import com.darwin.darwinMVC.mvc.Command;
	import com.darwin.darwinUI.manager.ToolTipManager;
	import com.darwin.darwinUI.manager.UIManager;
	import com.darwin.darwinUtils.Priority;
	import com.greensock.TweenLite;
	import com.greensock.easing.Linear;
	
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.filters.DropShadowFilter;
	import flash.filters.GlowFilter;
	import flash.filters.GradientGlowFilter;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	import flash.utils.getTimer;
	import flash.utils.setTimeout;
	
	import main.App;
	import main.AppConfig;
	import main.mvc.GController;
	
	import module.building.cmds.BuildCommand;
	import module.building.consts.BuildConst;
	import module.building.model.dataObj.BuildingObj;
	import module.edittroop.cmds.EditTroopCmdConst;
	import module.edittroop.model.dataObj.ArmsConfigObj;
	import module.edittroop.model.dataObj.HeroConfigObj;
	import module.scene.cmds.SceneCommand;
	import module.scene.cmds.SceneModelCommand;
	import module.scene.consts.ActionType;
	import module.scene.consts.SceneConst;
	import module.scene.event.JusticeIsoObjectEvent;
	import module.scene.event.JusticeIsoWorldEvent;
	import module.scene.model.SceneModelData;
	import module.scene.model.dataObj.IsoDataObj;
	import module.scene.model.dataObj.MapObj;
	import module.scene.model.dataObj.TerritoryIsoDataObj;
	import module.scene.model.dataObj.TroopIsoDataObj;
	import module.scene.utils.SceneUtil;
	import module.scene.view.JusticeIsoWorld;
	import module.scene.view.JusticeSceneView;
	import module.scene.view.group.BaseIsoGroup;
	import module.scene.view.iso.BuildingIsoObject;
	import module.scene.view.iso.CollectionIsoObject;
	import module.scene.view.iso.DecorationIsoObject;
	import module.scene.view.iso.FloorIsoObject;
	import module.scene.view.iso.TerritoryIsoObject;
	import module.scene.view.iso.TroopIsoObject;
	import module.scene.view.iso.base.JusticeIsoObject;
	import module.scene.view.nodes.TipNode;
	
	/**
	 *	场景控制器 
	 * @author Roland
	 * 
	 */
	public class SceneController extends GController
	{
		private var _sceneView:JusticeSceneView;
		private var _modelData:SceneModelData;
		private var _walkManager:WalkManager;
		private var _fogManager:FogManager;
		/**
		 *	实例化场景控制器 
		 */
		public function SceneController()
		{
			super();
		}
		
		override public function start():void
		{
			super.start();
			init();
		}
		
		private var _selectedItem:IsoObject;
		private var _dragItemList:Array;


				
		/**
		 *	以eid为索引的所有有eid的iso物件索引 
		 */
		private var _eIdIsoDic:Dictionary;
		/**
		 *	建筑字典 
		 */
		private var _buildingDic:Dictionary;
		/**
		 *	领地字典 
		 */
		private var _territoryDic:Dictionary;
		/**
		 *	部队字典 
		 */
		private var _troopDic:Dictionary;
		
		/**
		 *	城门字典 
		 */
		private var _gateDic:Dictionary;
		/**
		 * 场景静态数据字典 
		 */
		private var _sceneStaticDic:Dictionary = new Dictionary();
		private var _actionType:String = ActionType.NORMAL;
		
		
		private var _currentRegisterBlock:Array;
		
		/**
		 *	排队等待添加到场景的地图配置数据列表 
		 */
		private var _waitingMapDataList:Array = [];
		private var _mapCheckTimer:Timer;
		
		
		
		private function init():void
		{
			initModelData();
			initScene();
			initWorld();
			initWalkManager();
			initFogManager();
			initRegister();
			App.appStage.addEventListener(Event.RESIZE,onResize);
			
			_mapCheckTimer = new Timer(100);
			_mapCheckTimer.addEventListener(TimerEvent.TIMER,checkWaitingMapHandler);
			_mapCheckTimer.start();
		}
		
		private function initFogManager():void
		{
			_fogManager = new FogManager(_sceneView.fogLayer);
		}
		
		private function troopTest():void
		{
			var obj:TroopIsoDataObj;
			for (var i:int = 0; i < 1; i++) 
			{
				obj = new TroopIsoDataObj();
				obj.direction = 180;
				obj.serverId = "30001";
				obj.isoType = IsoType.OBJECT;
				obj.size = 2;
				obj.absX = _modelData.userTerritoryObj.absX + 2;
				obj.absZ = _modelData.userTerritoryObj.absZ + 10 +2 * i;
				obj.absY = 0;
				obj.troopName = "aaaaa";
				obj.armsId = "80001"
				obj.heroId = "10001";
				obj.troopId = int( 0xffffff * Math.random() ).toString();
				obj.userId = AppConfig.getInstance().userId;
				var cmd:Command = new Command(EditTroopCmdConst.EDIT_NEW_TROOP_SUCCESS);
				cmd.data = obj;
				troopHandler(cmd);
			}

		}
		
		
		private function initWalkManager():void
		{
			var aStar:AStar = new AStar();
			WalkManager.MAX_WALKER_SIZE = 2;
			_walkManager = new WalkManager(aStar,isoWorld.getMapGrid());
			_walkManager.addEventListener(WalkManagerEvent.WALKER_PATH_CHANGE,sendTroopPathChange);
		}
		
		private function sendTroopPathChange(event:WalkManagerEvent):void
		{
			var absPath:Array = gridPathToAbsPath(event.path);
			_modelData.sendTroopMoveInfo(event.walkerId,absPath);
			if(event.path.length==0){
				trace(event.path);
			}
		}
		
		private function initModelData():void
		{
			_modelData = new SceneModelData();
		}
		
		private function initScene():void
		{
			_sceneView = new JusticeSceneView(App.appStage);
			var $isoWorld:JusticeIsoWorld = new JusticeIsoWorld(_sceneView,SceneConst.X_NUM,SceneConst.Z_NUM,SceneConst.GRID_SIZE);
			$isoWorld.setFollowUpLayer(_sceneView.followUpLayer);
			appCommonView.sceneView = _sceneView;
//			$isoWorld.open9SceneGrid();
			_eIdIsoDic = new Dictionary();
			_troopDic = new Dictionary();
			_territoryDic = new Dictionary();
			_buildingDic = new Dictionary();
		}
		
		private function initWorld():void
		{
			isoWorld.addEventListener(JusticeIsoWorldEvent.ISO_ADD_TO_WORLD,onIsoWorldEvent)
			isoWorld.addEventListener(IsoWorldEvent.ISO_MAP_CHANGED,onMapChange);
			isoWorld.addEventListener(IsoWorldEvent.ISO_START_DRAG,onIsoWorldEvent);
			isoWorld.addEventListener(IsoWorldEvent.ISO_STOP_DRAG,onIsoWorldEvent);
			isoWorld.addEventListener(JusticeIsoWorldEvent.ISO_ADD_TO_WORLD,onIsoWorldEvent);
			isoWorld.addEventListener(JusticeIsoWorldEvent.ISO_REMOVE_FROM_WORLD,onIsoWorldEvent);
			isoWorld.addEventListener(IsoMouseEvent.ISO_MOUSE_DOWN,onIsoMouseDown);
			isoWorld.addEventListener(IsoMouseEvent.ISO_MOUSE_UP,onIsoMouseUp);
			isoWorld.addEventListener(IsoMouseEvent.ISO_MOUSE_MOVE, onIsoMouseMove);
			isoWorld.addEventListener(IsoMouseEvent.ISO_MOUSE_CLICK, onIsoMouseClick);
			isoWorld.addEventListener(IsoMouseEvent.ISO_MOUSE_CLICK_SPACE, onIsoMouseClickSpace);
		}

		
		private function initRegister():void
		{
			register(BuildCommand.CLICK_BUILD_OPEN_BUTTON, buildingHandler);
			register(BuildCommand.DIY_BUILD,buildingHandler);
			register(BuildCommand.DIY_MOVE,buildingHandler)
			register(BuildCommand.DIY_REMOVE,buildingHandler);
			register(BuildCommand.DIY_REMOVE_CONFIRM,buildingHandler);
			register(BuildCommand.DIY_MOVETOBAG,buildingHandler);

			register(BuildCommand.SELECT_BUILDLISTITEM, buildingHandler);
			register(BuildCommand.REMOVE_CURRENT_DRAGGING_BUILDING, buildingHandler);
			register(BuildCommand.DIY_CONFIRM, buildingHandler);
			register(BuildCommand.DIY_CANCEL, buildingHandler);
			register(BuildCommand.DIY_REVERT,revertHandler);
			
			
			register(EditTroopCmdConst.EDIT_NEW_TROOP_SUCCESS,troopHandler);
			register(EditTroopCmdConst.DELETE_TROOP_FROM_MODEL,troopHandler);
			
			register(SceneModelCommand.MAP_BUILDING_LIST_UPDATE,buildingInfoHandler);
			register(SceneModelCommand.ADD_BUILDING_LIST_UPDATE,buildingInfoHandler);
			register(SceneModelCommand.REMOVE_BUILDING_LIST_UPDATE,buildingInfoHandler);
			register(SceneModelCommand.MOVE_BUILDING_LIST_UPDATE,buildingInfoHandler);
			
			register(SceneModelCommand.GET_TERRITORY_POSITION,territoryHandler);
			register(SceneCommand.SCENE_CMD_LOCATE_HOME,territoryHandler);
			
			register(SceneModelCommand.TROOP_PATH_CHANGED,troopHandler);
			register(SceneCommand.SCENE_CMD_LOCATE_TROOP,troopHandler);
			
			register(SceneCommand.SCENE_CMD_MODIFY_ISOOBJECT,isoModifyHandler);
			register(SceneCommand.SCENE_CMD_DROP_ITEM,dropItemHandler,-1);
		}
		
		/**
		 *	物品掉落中转处理，添加一些必要属性，这里处理完会自动转入mainController中的处理函数 
		 * @param cmd
		 * 
		 */
		private function dropItemHandler(cmd:SceneCommand):void
		{
//			cmd.pause();
		 	var $data:Object = cmd.data;
			var $position:Point;

			if($data.hasOwnProperty("eId"))
			{
				var $iso:JusticeIsoObject = _eIdIsoDic[$data.eId];
				if($iso)
				{
					$data.size = $iso.size;
					$position = IsoUtils.isoToScreen($iso.postion3D);
					$position.offset(isoWorld.contentX,isoWorld.contentY);
					$data.x = $position.x;
					$data.y = $position.y;
				}
			}
//			cmd.proceed();
		}
		
		private var _waitingHandleBuildingInfoCmds:Array = [];//等待处理的buildingInfo相关命令，等获取领地之后再做处理
		private function buildingInfoHandler(cmd:SceneModelCommand):void
		{
			if(_modelData.userTerritoryObj==null)//TODO 等库中锁定解锁方法写完后删除，转去使用modelData的命令锁定方式处理
			{
				_waitingHandleBuildingInfoCmds.push(cmd);
				return;
			}
			var list:Array;

			switch(cmd.cmdName)
			{
				
				case SceneModelCommand.MAP_BUILDING_LIST_UPDATE:
				{
					for(var key:String in _buildingDic) 
					{
						isoWorld.removeFromWorld(_buildingDic[key]);
					}
					list = cmd.data as Array;
					createBuilding(list);
					updateCombo();
					break;
				}
				case SceneModelCommand.ADD_BUILDING_LIST_UPDATE:
				{
					list = cmd.data as Array;
					createBuilding(list);
					updateCombo();
					break;
				}
				case SceneModelCommand.REMOVE_BUILDING_LIST_UPDATE:
				{
					list = cmd.data as Array;
					deleteBuilding(list);
					break;
				}
				case SceneModelCommand.MOVE_BUILDING_LIST_UPDATE:
				{
					list = cmd.data as Array;
					moveBuilding(list);
					break;
				}
				default:
				{
					break;
				}
			}
			function moveBuilding(list:Array):void
			{
				for (var i:int = 0; i < list.length; i++) 
				{
					var isoDataObj:IsoDataObj = list[i].isoDataObj;
					var dataObj:Object = list[i].dataObj;
					var iso:JusticeIsoObject = _eIdIsoDic[isoDataObj.eId];
					if(iso)
					{
						iso.isoDataObj = isoDataObj;
						iso.dataObj = dataObj;
						iso.postion3D = isoDataObj.postion3D;
						if(iso is TerritoryIsoObject)
						{
							
						}else if(iso is BuildingIsoObject){
							
						}
					}
				}
			}
			
			function deleteBuilding(list:Array):void
			{
				for (var i:int = 0; i < list.length; i++) 
				{
					var isoDataObj:IsoDataObj = list[i].isoDataObj;
					var dataObj:Object = list[i].dataObj;
					var key:String = isoDataObj.absX + "_" + isoDataObj.absZ;
					var iso:JusticeIsoObject;
					if(_buildingDic[key] != null)
					{
						iso = _buildingDic[key] as JusticeIsoObject;
						if(iso.parentWorld)
						{
							isoWorld.removeFromWorld(iso);
						}else{
							iso.dispose();
							delete _buildingDic[key];
						}
					}
				}
			}
			
			function createBuilding(list:Array):void
			{
				list.sort(buildingSortFn);//基于xz排序，从屏幕上方向下逐行添加，保证城门等组合体第一部分先被添加
				for (var i:int = 0; i < list.length; i++) 
				{
					var isoDataObj:IsoDataObj = list[i].isoDataObj;
					var dataObj:BuildingObj = list[i].dataObj as BuildingObj;
					var key:String = isoDataObj.absX + "_" + isoDataObj.absZ;
					var absPos:IsoPosition = new IsoPosition(isoDataObj.absX,isoDataObj.absZ);
					var iso:BuildingIsoObject;
					if(isIn9Scene(absPos) == false) continue;//不处理9屏外的数据
					if(_buildingDic[key] == null)
					{
						switch(dataObj.subType)
						{
							case BuildConst.SUBTYPE_GATE://城门，添加群组
							{
								var pos:IsoPosition = SceneUtil.absPosToRelPos(isoDataObj.absX,isoDataObj.absZ);
								var isoArr:Array = addGateToWorld(isoDataObj,dataObj,pos);
								break;
							}
							default:
							{
								iso = new BuildingIsoObject(isoDataObj,dataObj);
								iso.postion3D = isoDataObj.postion3D;
								isoWorld.addToWorld(iso);
								break;
							}
						}
					}else{
						iso = _buildingDic[key] as BuildingIsoObject;
						iso.isoDataObj = isoDataObj;
						iso.dataObj = dataObj;
						iso.postion3D = isoDataObj.postion3D;
						_eIdIsoDic[isoDataObj.eId] = iso;
					}
					if(iso && iso.isCombo)
					{
						_comboLinkedList.push(iso);
					}
				}
			}
			
			function buildingSortFn(a:Object,b:Object):int
			{
				var $isoDataObjA:IsoDataObj = a.isoDataObj;
				var $isoDataObjB:IsoDataObj = b.isoDataObj;
				if(($isoDataObjA.absX + $isoDataObjA.absZ) > ($isoDataObjB.absX + $isoDataObjB.absZ))
				{
					return 1;
				}else if(($isoDataObjA.absX + $isoDataObjA.absZ) == ($isoDataObjB.absX + $isoDataObjB.absZ))
				{
					return 0;
				}else{
					return -1;
				}
			}
		}
		
		private function territoryHandler(cmd:Command):void
		{
			switch(cmd.cmdName)
			{
				case SceneModelCommand.GET_TERRITORY_POSITION:
				{
					if( _modelData.userTerritoryObj)
					{
						locatedToTerritory(_modelData.userTerritoryObj,false);
						isoWorld.checkSceneFlag();//主动更新9屏信息
					}
					//TODO 临时处理办法，等待收到领地信息后再处理建筑更新信息，库中锁定解锁命令完成后统一在ModelData中处理
					while(_waitingHandleBuildingInfoCmds.length>0)
					{
						buildingInfoHandler(_waitingHandleBuildingInfoCmds.pop() as SceneModelCommand);
					}
					break;
				}
				case SceneCommand.SCENE_CMD_LOCATE_HOME:
				{
					if( _modelData.userTerritoryObj)
					{
						locatedToTerritory(_modelData.userTerritoryObj,true);
					}
//					troopTest();

					break;
				}
				default:
				{
					break;
				}
			}

		}
		
		private function troopHandler(cmd:Command):void
		{
			var troopId:String = cmd.data.troopId;
			switch(cmd.cmdName)
			{
				case EditTroopCmdConst.EDIT_NEW_TROOP_SUCCESS:
				{
					var obj:TroopIsoDataObj = cmd.data as TroopIsoDataObj;
					if(_troopDic[obj.troopId] != null)return;
					var iso:JusticeIsoObject;
					if(obj)
					{
						iso = addIsoToWorld(obj,true) as JusticeIsoObject;
						var tryResult:IsoTryResult = isoWorld.tryHandler(iso);
						var count:int = 0;
//						while(tryResult.isSucess == false)
//						{
//							
//							iso.x3d += SceneConst.GRID_SIZE * 2 * int((count+1)/5);
//							iso.z3d += SceneConst.GRID_SIZE * 2 * (count % 5);
//							tryResult = isoWorld.tryHandler(iso);
//							count++;
//						}
						
						var gridPosition:IsoPosition = getPositionInMapGrid(iso.isoPosition);
						_walkManager.addWalker(obj.troopId,gridPosition.x,gridPosition.z,2,true);
						if(obj.userId == AppConfig.getInstance().userId)
						{
							_walkManager.setEndPos(obj.troopId,gridPosition.x,gridPosition.z);
						}
						if(iso.userId == AppConfig.getInstance().userId)
						{
							iso.openFieldVisible = true;//己方部队，打开视野
						}else{
							iso.openFieldVisible = false;
						}
						_troopDic[obj.troopId] = iso;
						
						var $cmd:SceneCommand = new SceneCommand(SceneCommand.SCENE_CMD_TROOPLIST_CHANGED);
						var $list:Array = [];
						for each (var troopObj:TroopIsoObject in _troopDic) 
						{
							if(troopObj.userId == AppConfig.getInstance().userId)
							{
								$list.push(troopObj.isoDataObj);
							}
						}
						$cmd.data = $list;
						dispatch($cmd);
					}
					break;
				}
				case EditTroopCmdConst.DELETE_TROOP_FROM_MODEL:
				{
					if(cmd.data)
					{
						for each (var troopIso:TroopIsoObject in _troopDic) 
						{
							if(troopIso.troopId == cmd.data.troopId)
							{
								isoWorld.removeFromWorld(troopIso);
								delete _troopDic[troopIso];
								break;
							}
						}
					}
					break;
				}
				case SceneModelCommand.TROOP_PATH_CHANGED:
				{
					var path:Array = absPathToGridPath(cmd.data.path);
					if(_troopDic[troopId] != null)
					{
						var $iso:TroopIsoObject = _troopDic[troopId] as TroopIsoObject;
						if($iso.disposed == false)
						{
							_walkManager.setPath(troopId,path);
							moveTroop(_troopDic[troopId]);
						}else{
							_walkManager.removeWalker(troopId);
							delete _troopDic[troopId];
						}
					}
					break;
				}
				case SceneCommand.SCENE_CMD_LOCATE_TROOP:
				{
					if(_troopDic[troopId] != null)
					{
						locatedToIso(_troopDic[troopId]);
					}
				}
			}
		}
		
		private function buildingHandler(cmd:BuildCommand):void
		{
			switch (cmd.cmdName)
			{
				case BuildCommand.DIY_BUILD:
					if(_selectedItem)
					{
						isoWorld.hideGrid(_selectedItem);
						_selectedItem = null;
					}
					removeDragItems();
					actionType = ActionType.BUILD;
					break;
				case BuildCommand.DIY_MOVE:
					if(_selectedItem)
					{
						isoWorld.hideGrid(_selectedItem);
						_selectedItem = null;
					}
					removeDragItems();
					actionType = ActionType.MOVE;
					break;
				case BuildCommand.DIY_REMOVE:
					if(_selectedItem)
					{
						isoWorld.hideGrid(_selectedItem);
						_selectedItem = null;
					}
					removeDragItems();
					actionType = ActionType.REMOVE;
					break;
				case BuildCommand.DIY_MOVETOBAG:
					if(_selectedItem)
					{
						isoWorld.hideGrid(_selectedItem);
						_selectedItem = null;
					}
					removeDragItems();
					actionType = ActionType.MOVETOBAG;
					break;
				case BuildCommand.SELECT_BUILDLISTITEM:			
				{
					var dataObj:BuildingObj = cmd.data as BuildingObj;//这是BuildingController传过来的数据，包含的是所选Item对应的建筑物信息BuildingObj
					var isoData:IsoDataObj = _modelData.getIsoObjById(dataObj.serverId).clone();//new IsoDataObj();
					var pos:IsoPosition;

					switch(dataObj.subType)
					{
						case BuildConst.SUBTYPE_GATE://城门，需要群组移动
						{
							pos = isoWorld.getGridPoint3D(App.appStage.mouseX,App.appStage.mouseY);
							dragItemList = addGateToWorld(isoData,dataObj,pos);
							isoWorld.showGridByList(dragItemList);
							var centerPoint:Point = new Point(dragItemList[2].x + isoWorld.contentX,dragItemList[2].y + isoWorld.contentY);//定位到中心
							isoWorld.startDragIsoObjectList(dragItemList,centerPoint);
							break;
						}	
						default:
						{
							var building:BuildingIsoObject = new BuildingIsoObject(isoData,dataObj);
							var point:Point = new Point(App.appStage.mouseX,App.appStage.mouseY);
							pos = isoWorld.getGridPoint3D(App.appStage.mouseX,App.appStage.mouseY);
							building.x3d = pos.x*SceneConst.GRID_SIZE;
							building.z3d = pos.z*SceneConst.GRID_SIZE;
							building.clickEnabled = false;
							building.mouseHoverEnabled = false;
							building.openFieldVisible = false;
							building.hideWithFog = false;
							dragItemList = [building];
							isoWorld.addToWorldByList(dragItemList);
							isoWorld.startDragIsoObjectList(dragItemList,point);
							if(isoWorld.tryHandler(building).isSucess)
							{					
								isoWorld.showGrid(building,false,0x00ff00,2);
							}else
							{
								isoWorld.showGrid(building,false);
							}
							break;
						}
					}

					break;
				}
				case BuildCommand.REMOVE_CURRENT_DRAGGING_BUILDING:
					removeDragItems();
					break;
				case BuildCommand.DIY_CONFIRM:
					if(_selectedItem)
					{
						isoWorld.hideGrid(_selectedItem);
						_selectedItem = null;
					}
					removeDragItems();
					actionType = ActionType.NORMAL;
					break;
				case BuildCommand.DIY_CANCEL:
					if(_selectedItem)
					{
						isoWorld.hideGrid(_selectedItem);
						_selectedItem = null;
					}
					removeDragItems();
					actionType = ActionType.NORMAL;
					break;
				case BuildCommand.DIY_REMOVE_CONFIRM://执行remove/moveobag模式下的确认删除动作
					var $targetIso:JusticeIsoObject = cmd.data as JusticeIsoObject;
					if($targetIso)
					{
						var $dCmd:SceneCommand;
						isoWorld.removeFromWorld($targetIso);
						$dCmd = new SceneCommand(SceneCommand.SCENE_ACTION_REMOVE);
						$dCmd.target = $targetIso;
						$dCmd.actionType = actionType;
						dispatch($dCmd);
					}
					break;
				default:
					break;
			}
		}

		/**
		 *	撤销动作处理 
		 * @param cmd
		 * 
		 */
		private function revertHandler(cmd:BuildCommand):void
		{
			var $list:Array = cmd.data as Array;
			for (var i:int = 0; i < $list.length; i++) 
			{
				var $actionCmd:SceneCommand = $list[i] as SceneCommand;
				if($actionCmd)
				{
					switch($actionCmd.cmdName)
					{
						case SceneCommand.SCENE_ACTION_ADD:
						{
							if($actionCmd.target)
							{
								isoWorld.removeFromWorld($actionCmd.target as IsoObject);
							}
							break;
						}
						case SceneCommand.SCENE_ACTION_MOVE:
						{
							var $from:Point3D = $actionCmd.data.from;
							if($from && $actionCmd.target)
							{
								($actionCmd.target as IsoObject).postion3D = $from;
							}
							break;
						}
						case SceneCommand.SCENE_ACTION_REMOVE:
						{
							if($actionCmd.target)
							{
								var $iso:Object = $actionCmd.target;
								var $qIso:JusticeIsoObject = $iso as JusticeIsoObject;
								if($qIso.disposed = true)
								{
									var $class:Class = getDefinitionByName(getQualifiedClassName($iso)) as Class;
									var $newIso:JusticeIsoObject = new $class($qIso.isoDataObj,$qIso.dataObj);
									$newIso.x3d = $qIso.x3d;
									$newIso.z3d = $qIso.z3d;
									isoWorld.addToWorld($newIso);
								}else{
									isoWorld.addToWorld($qIso);
								}
							}
							break;
						}
					}
				}
			}
			
		}
		
		
		private function isoModifyHandler(cmd:SceneCommand):void
		{
			var $orgData:Object = cmd.data;
			var $dataArr:Array;
			if($orgData is Array)
			{
				$dataArr = $orgData as Array;
			}else{
				$dataArr = [$orgData];
			}
			if($dataArr)
			{
				for (var i:int = 0; i < $dataArr.length; i++) 
				{
					var $data:Object = $dataArr[i];
					if($data.hasOwnProperty("eId"))
					{
						var $iso:JusticeIsoObject = _eIdIsoDic[$data.eId] as JusticeIsoObject;
						var $isoDataObj:IsoDataObj = $iso.isoDataObj.clone();
						var $dataObj:Object = ($iso.dataObj as BuildingObj).clone();
						if($iso)
						{
							var param:String;
							if($data.hasOwnProperty("isoDataObj"))
							{
								var $isoDataObjParams:Object = $data.isoDataObj;
								for(param in $isoDataObjParams)
								{
									if($isoDataObj.hasOwnProperty(param))$isoDataObj[param] = $isoDataObjParams[param];
								}
								$iso.isoDataObj  = $isoDataObj;
							}
							
							if($data.hasOwnProperty("dataObj"))
							{
								var $dataObjParams:Object = $data.dataObj;
								for(param in $dataObjParams)
								{
									if($dataObj.hasOwnProperty(param))
									{
										$dataObj[param] = $dataObjParams[param];
									}
								}
								$iso.dataObj = $dataObj;
							}
						}
					}
				}
			}
			
		}
		
		private function removeDragItems():void
		{
			if(dragItemList && dragItemList.length>0)
			{
				switch (actionType)
				{
					case ActionType.BUILD://从场景上移除
						isoWorld.hideGridByList(dragItemList);
						isoWorld.removeFromWorldByList(dragItemList);
						dragItemList = null;
						break;
					case ActionType.REMOVE:
						//应当不可能进来
						break;
					case ActionType.MOVE://移回原位
						isoWorld.hideGridByList(dragItemList);
						isoWorld.stopDragIsoObject(true);
						dragItemList = null;
						break;
					case ActionType.MOVETOBAG:
						//应当不可能进来
						break;
					case ActionType.NORMAL:
						break;
				}

			}
		}
		
		/**
		 * iso对象命令转发 
		 * @param e
		 * 
		 */
		private function onIsoDispatchEvent(e:JusticeIsoObjectEvent):void
		{
			var $iso:JusticeIsoObject = e.target as JusticeIsoObject;
			var $event:Event = e.data as Event;
			var $cmd:SceneCommand = new SceneCommand(SceneCommand.SCENE_CMD_ISO_DISPATCH_EVENT,$iso);
			$cmd.data = {"event":$event,"isoDataObj":$iso.isoDataObj,"dataObj":$iso.dataObj};
			dispatch($cmd);
		}
		
		private function onIsoWorldEvent(e:IsoWorldEvent):void
		{
			var $cmd:SceneCommand; 
			var $absPos:IsoPosition;
			var $key:String;

			switch(e.type)
			{
				case IsoWorldEvent.ISO_START_DRAG:
				{
					$cmd = new SceneCommand(SceneCommand.SCENE_CMD_STARTDRAG);
					$cmd.actionType = actionType;
					dispatch($cmd);
					break;
				}
				case IsoWorldEvent.ISO_STOP_DRAG:
				{
					$cmd = new SceneCommand(SceneCommand.SCENE_CMD_STOPDRAG);
					$cmd.actionType = actionType;
					dispatch($cmd);
					break;
				}
				case JusticeIsoWorldEvent.ISO_ADD_TO_WORLD:
				{
					var $addedIso:JusticeIsoObject = e.data as JusticeIsoObject;
					$addedIso.addEventListener(JusticeIsoObjectEvent.ISO_DISPATCH_EVENT,onIsoDispatchEvent);
					$absPos = $addedIso.absIsoPosition;
					$key = $absPos.x + "_" + $absPos.z;
					if($addedIso is TerritoryIsoObject)
					{
						_territoryDic[$key] = $addedIso;
						updateTerritoryGrid();
					}else if($addedIso is BuildingIsoObject)
					{
						_buildingDic[$key] = $addedIso;
					}
					_eIdIsoDic[$addedIso.isoDataObj.eId] = $addedIso;
					break;
				}
				case JusticeIsoWorldEvent.ISO_REMOVE_FROM_WORLD:
				{
					var $removedIso:JusticeIsoObject = e.data as JusticeIsoObject;
					$removedIso.removeEventListener(JusticeIsoObjectEvent.ISO_DISPATCH_EVENT,onIsoDispatchEvent);
					$absPos = $removedIso.absIsoPosition;
					$key = $absPos.x + "_" + $absPos.z;
					if($removedIso is TerritoryIsoObject)
					{
						delete _territoryDic[$key];
					}else if($removedIso is BuildingIsoObject)
					{
						delete _buildingDic[$key];
					}
					delete _eIdIsoDic[$removedIso.isoDataObj.eId];
					break;
				}
				default:
				{
					break;
				}
			}

		}
		
		private function onIsoMouseUp(e:IsoMouseEvent):void
		{
			var $cmd:SceneCommand = new SceneCommand(SceneCommand.SCENE_CMD_MOUSE_UP);
			var $pos:IsoPosition = isoWorld.getGridPoint3D(App.appStage.mouseX,App.appStage.mouseY);
			$cmd.actionType = actionType;
			$cmd.data = {isoPosition:$pos};
			dispatch($cmd);
		}
		
		private function onIsoMouseDown(e:IsoMouseEvent):void
		{
			var targetIso:IsoObject = e.nodeContainer as IsoObject;
			var $cmd:SceneCommand = new SceneCommand(SceneCommand.SCENE_CMD_MOUSE_DOWN);
			$cmd.actionType = actionType;
			$cmd.target = targetIso;
			dispatch($cmd);
		}
		
		private function onIsoMouseMove(e:IsoMouseEvent):void
		{
			if(dragItemList && dragItemList.length>0)
			{
				isoWorld.updateDragIsoObjectList(new Point(App.appStage.mouseX,App.appStage.mouseY));
				var color:uint;
				if(isoWorld.tryHandlerByList(dragItemList) && isInTerritoryRangeByList(dragItemList))
				{
					color = 0x00ff00;
				}else
				{
					color = 0xff0000;
				}
				isoWorld.moveGridByList(dragItemList,color);
				updateCombo();
			}
			else if(_selectedItem)
			{
				
			}
			else
			{
				
			}
			var $cmd:SceneCommand = new SceneCommand(SceneCommand.SCENE_CMD_MOUSE_MOVE);
			$cmd.actionType = actionType;
			var targetIso:IsoObject = e.nodeContainer as IsoObject;
			if(targetIso)
			{
				var $position:Point = IsoUtils.isoToScreen(targetIso.postion3D);
				$position.offset(isoWorld.contentX,isoWorld.contentY);
				$cmd.data = {point:$position};
				$cmd.target = targetIso;
			}
			dispatch($cmd);
			
//			trace(targetIso,":",_fogManager.isInFog(targetIso))
		}
		
		private function onIsoMouseClick(e:IsoMouseEvent):void
		{
			var $targetIso:JusticeIsoObject = e.nodeContainer as JusticeIsoObject;
			var $targetNode:Node = e.nodeTarget as Node;
			if($targetIso)
			{
				exeIsoClick($targetIso);
			}else if($targetNode)
			{
				exeNodeClick($targetNode);
			}
		}
		
		
		private function exeIsoClick(target:JusticeIsoObject):void
		{
			var $targetIso:JusticeIsoObject = target;
			if($targetIso==null)return;
			var $cmd:SceneCommand;
			var $position:Point;
			
			switch(actionType)
			{
				case ActionType.NORMAL://普通操作模式下
					var canSelect:Boolean = false;
					if($targetIso is TroopIsoObject)//点击部队
					{
						var $troop:TroopIsoObject = $targetIso as TroopIsoObject;
						if($troop.userId == AppConfig.getInstance().userId)
						{
							canSelect = true;
						}
					}
					else if($targetIso is BuildingIsoObject)//点击建筑
					{
						canSelect = true;
						isoWorld.hideGrid($targetIso);
					}
					if(canSelect)
					{
						isoWorld.hideGrid(_selectedItem);		
						_selectedItem = $targetIso;
						isoWorld.showGrid(_selectedItem);
					}
					$cmd = new SceneCommand(SceneCommand.SCENE_CMD_CLICK_ISO);
					$position = IsoUtils.isoToScreen($targetIso.postion3D);
					$position.offset(isoWorld.contentX,isoWorld.contentY);
					$cmd.data = {point:$position};
					$cmd.target = $targetIso;
					$cmd.actionType = actionType;
					dispatch($cmd);
					break;
				case ActionType.BUILD:
					if(dragItemList && dragItemList.length > 0)
					{
						onIsoMouseClickSpace(new IsoMouseEvent(IsoMouseEvent.ISO_MOUSE_CLICK_SPACE));
					}
					break;
				case ActionType.MOVE:
					var $point:Point;// = new Point(App.appStage.mouseX,App.appStage.mouseY);
					if($targetIso.parts && $targetIso.parts.length > 0)//如果为组合部件
					{
						var $part:JusticeIsoObject;
						for (var i:int = 0; i < $targetIso.parts.length; i++) 
						{
							$part = $targetIso.parts[i];
							$part.clickEnabled = false;
							$part.mouseHoverEnabled = false;
						}
						var $centerPartIndex:int = Math.floor($targetIso.parts.length / 2);
						$point = new Point($targetIso.parts[$centerPartIndex].x + isoWorld.contentX,$targetIso.parts[$centerPartIndex].y + isoWorld.contentY);
						dragItemList = $targetIso.parts;
					}else{
						$targetIso.clickEnabled = false;
						$targetIso.mouseHoverEnabled = false;
						$point = new Point(App.appStage.mouseX,App.appStage.mouseY);
						dragItemList =[$targetIso];
					}
					isoWorld.showGridByList(dragItemList);
					isoWorld.startDragIsoObjectList(dragItemList,$point);
					break;
				case ActionType.REMOVE:
				case ActionType.MOVETOBAG://移除操作
					if($targetIso.parts && $targetIso.parts.length > 0){ //组合部件，删除所有部件，无需确认直接拆除
						var parts:Array = $targetIso.parts;
						isoWorld.removeFromWorldByList(parts);
						for (var j:int = 0; j < parts.length; j++) 
						{
							var $removedIso:JusticeIsoObject = parts[j];
							$cmd = new SceneCommand(SceneCommand.SCENE_ACTION_REMOVE);
							$cmd.target = $removedIso;
							$cmd.actionType = actionType;
							dispatch($cmd);
						}
					}else if($targetIso.isoDataObj.placedConsecutively==true)//连续拆除模式，无需确认直接拆除
					{
						isoWorld.removeFromWorld($targetIso);
						$cmd = new SceneCommand(SceneCommand.SCENE_ACTION_REMOVE);
						$cmd.target = $targetIso;
						$cmd.actionType = actionType;
						dispatch($cmd);
					}else{//只抛点击命令,等待确认再删除
						$cmd = new SceneCommand(SceneCommand.SCENE_CMD_CLICK_ISO);
						$position = IsoUtils.isoToScreen($targetIso.postion3D);
						$position.offset(isoWorld.contentX,isoWorld.contentY);
						$cmd.data = {point:$position};
						$cmd.target = $targetIso;
						$cmd.actionType = actionType;
						dispatch($cmd);
					}
					if($targetIso.isCombo)
					{
						updateSingleCombo($targetIso,1);
					}
					break;
			}
		}
		
		private function exeNodeClick(targetNode:Node):void
		{
			if(targetNode == null)return;
			var $cmd:SceneCommand;
			if(targetNode is TipNode)
			{
				var $tipNode:TipNode = targetNode as TipNode;
				var $iso:JusticeIsoObject = $tipNode.parentContainer as JusticeIsoObject;
				var $isoDataObj:IsoDataObj = $iso.isoDataObj;
				var $dataObj:Object = $iso.dataObj;
				$cmd = new SceneCommand(SceneCommand.SCENE_CMD_CLICK_ISOTIPNODE,$tipNode.source);
				$cmd.data = {"isoDataObj":$isoDataObj,"dataObj":$dataObj};
				dispatch($cmd);
			}
		}
		
		private function onIsoMouseClickSpace(e:IsoMouseEvent):void
		{
			var $cmd:SceneCommand;

			if(dragItemList && dragItemList.length > 0 && isoWorld.tryHandlerByList(dragItemList) && isInTerritoryRangeByList(dragItemList))
			{
				var orgPointList:Array = isoWorld.originalIsoObjectPoints;
				isoWorld.stopDragIsoObject();
				isoWorld.hideGridByList(dragItemList);
				for (var i:int = 0; i < dragItemList.length; i++) 
				{
					var item:JusticeIsoObject = dragItemList[i];
					item.clickEnabled = true;
					item.mouseHoverEnabled = true;
					item.openFieldVisible = true;
					item.hideWithFog = true;
				}

				
				var $tempDic:Dictionary = new Dictionary();
				for(var $oldKey:String in _buildingDic) 
				{
					$tempDic[_buildingDic[$oldKey]] = $oldKey;
				}
				for(var $item:Object in $tempDic)
				{
						delete _buildingDic[$tempDic[$item]];
				}
	
				for (var j:int = 0; j < dragItemList.length; j++) 
				{
					var $dragItem:JusticeIsoObject = dragItemList[j] as JusticeIsoObject;
					var $absPos:IsoPosition = $dragItem.absIsoPosition;
					var $key:String = $absPos.x + "_" + $absPos.z;
					_buildingDic[$key] = $dragItem;
					switch(actionType)
					{
						case ActionType.BUILD:
							$cmd = new SceneCommand(SceneCommand.SCENE_ACTION_ADD);
							$cmd.data = $dragItem.dataObj;
							$cmd.target = $dragItem;
							dispatch($cmd);
							break;
						case ActionType.MOVE:
							$cmd = new SceneCommand(SceneCommand.SCENE_ACTION_MOVE);
							$cmd.target = $dragItem;
							$cmd.actionType = actionType;
							$cmd.data = {"from":orgPointList[j],"to":$dragItem.postion3D};
							dispatch($cmd);
							break;
					}
				}
				if(actionType == ActionType.BUILD && dragItemList[0].isoDataObj.placedConsecutively == true)//连续建造，模拟抛送建筑选择命令
				{
					var $buildcmd:BuildCommand = new BuildCommand(BuildCommand.SELECT_BUILDLISTITEM);
					$buildcmd.data = $dragItem.dataObj;
					buildingHandler($buildcmd);
				}else{
					dragItemList = null;
				}
				orgPointList = null;
				updateMapGrid(true);
			}//if
			else if(_selectedItem)
			{
				if(_selectedItem is TroopIsoObject)
				{
					var pos:IsoPosition = isoWorld.getGridPoint3D(App.appStage.mouseX,App.appStage.mouseY);
					var walkablePos:IsoPosition = getWalkablePlace(_selectedItem,pos);
					if(walkablePos)
					{
						var gridPosition:IsoPosition = getPositionInMapGrid(walkablePos);
						var curruntEndPos:Object = _walkManager.getEndPos((_selectedItem as TroopIsoObject).troopId);
						if(curruntEndPos.x != gridPosition.x || curruntEndPos.y != gridPosition.z)//如果终点更换了，则重新寻路
						{
							_walkManager.setEndPos((_selectedItem as TroopIsoObject).troopId,gridPosition.x,gridPosition.z);//设置路径但不移动，等待后台推送路径返回
						}
					}
				}
				else if(_selectedItem is BuildingIsoObject)
				{
					isoWorld.hideGrid(_selectedItem);
					_selectedItem = null;
				}

			}
			$cmd = new SceneCommand(SceneCommand.SCENE_CMD_CLICK_SPACE);
			var $pos:IsoPosition = isoWorld.getGridPoint3D(App.appStage.mouseX,App.appStage.mouseY);
			$cmd.actionType = actionType;
			$cmd.data = {isoPosition:$pos};
			dispatch($cmd);
		}
		
		/**
		 *	判断一组物件是否都在领地范围内 
		 * @param isoList
		 * @return 
		 * 
		 */
		private function isInTerritoryRangeByList(isoList:Array):Boolean
		{
			if(isoList == null || isoList.length == 0) return false;
			for (var i:int = 0; i < isoList.length; i++) 
			{
				var $iso:IsoObject = isoList[i] as IsoObject;
				if($iso)
				{
					var $result:Boolean = isInTerritoryRange($iso);
					if($result == false)
					{
						return false;
					}
				}
			}
			return true;
		}
		
		/**
		 *	判断传入物件是否在领地范围内 
		 * @param iso
		 * 
		 */
		private function isInTerritoryRange(iso:IsoObject):Boolean
		{
			var territoryObj:TerritoryIsoDataObj = _modelData.userTerritoryObj;
			if(territoryObj)
			{
				var pos:IsoPosition = SceneUtil.absPosToRelPos(territoryObj.absX,territoryObj.absZ);
				var offsetX:int = (iso.isoPosition.x - pos.x);
				var offsetZ:int = (iso.isoPosition.z - pos.z)
				if(offsetX >= 0 && offsetX<=(territoryObj.rangeWidth-iso.floorWidth/iso.size) && offsetZ >= 0 && offsetZ<=(territoryObj.rangeHeight-iso.floorHeight/iso.size))
				{
					return true;
				}
			}
			return false;
		}
		
		/**
		 *	判断传入的绝对坐标(基于格子)是否在当前9屏范围内 
		 * @param absIsoPosition
		 * @return 
		 */
		private function isIn9Scene(absIsoPosition:IsoPosition):Boolean
		{
			var $current9Scenes:Array = isoWorld.current9SceneArr;
			var $registerBlock:Array = $current9Scenes[0];//注册点块 
			var $minX:uint = ($registerBlock[0] + SceneConst.CENTER_BLOCK_X)*SceneConst.X_NUM;
			var $minZ:uint = ($registerBlock[1] + SceneConst.CENTER_BLOCK_Z)*SceneConst.Z_NUM;
			var $maxX:uint = $minX + 3 * SceneConst.X_NUM;
			var $maxZ:uint = $minZ + 3 * SceneConst.Z_NUM;
			if(absIsoPosition.x >= $minX && absIsoPosition.x <= $maxX 
				&& absIsoPosition.z >= $minZ && absIsoPosition.z <= $maxZ )
			{
				return true;
			}
			return false;
		}
		
		/**
		 *	在isoPos给定的位置附近寻找一个可以放下iso让其走过去的点
		 * @param iso 要测试的iso
		 * @param isoPos 要测试的格子坐标
		 * @return 找到的格子坐标，如果没找到则返回null
		 * 
		 */
		private function getWalkablePlace(iso:IsoObject,isoPos:IsoPosition):IsoPosition
		{
			var $factor:int = -1;
			var $pointArr:Array = [[0,0],[0,-1],[-1,-1],[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-2],[0,-2],[-1,-2],[-2,-2],[-2,-1],[-2,0],[-2,1],[-2,2],[-1,2],[0,2],[1,2],[2,2],[2,1],[2,0],[2,-1],[2,-2]];
			//TODO 螺旋向外遍历
			for (var i:int = 0; i < $pointArr.length; i++) 
			{
				var $offsetX:int = $pointArr[i][0];
				var $offsetZ:int = $pointArr[i][1];
				var tryResult:IsoTryResult = isoWorld.tryHandler(iso,App.appStage.mouseX + $offsetX*SceneConst.GRID_SIZE,App.appStage.mouseY + $offsetZ*SceneConst.GRID_SIZE);
				trace(tryResult.isoPosition);
				if(tryResult.isSucess)
				{
					return tryResult.isoPosition;
				}
			}
			return null;
		}
		
		/**
		 *	根据地图配置数据添加物件 
		 * @param mapData 地图配置数据
		 * @param offsetX 地图块横向偏移(格)
		 * @param offsetZ 地图块纵向偏移(格)
		 * 
		 */
		private function addObjectsByMapData(mapData:Object,offsetX:int,offsetZ:int):void
		{
			var mapObj:MapObj = MapObj.parseData(mapData);
			var objectArray:Array = mapObj.dataArray;
			var isoObjArray:Array = [];
			var obj:IsoDataObj;
			var iso:IsoObject;
			for (var j:int = 0; j < objectArray.length; j++) 
			{
				var itemData:Object = objectArray[j];
				obj = _modelData.getIsoObjById(itemData.id);
				obj.direction = itemData.direction;
				obj.absX = itemData.x/SceneConst.GRID_SIZE + offsetX;
				obj.absY = itemData.y;
				obj.absZ = itemData.z/SceneConst.GRID_SIZE + offsetZ;
				obj.comboRim = itemData.comboRim;
				addIsoToWorld(obj);
			}
		}
		
		private function addIsoToWorld(obj:IsoDataObj,clickEnable:Boolean = false):IsoObject
		{
			var isoClass:Class =  serverIdToIsoClass(obj.serverId);
			var iso:IsoObject = new isoClass(obj);
			iso.isoType = obj.isoType;
			iso.postion3D = obj.postion3D;
			iso.direction = obj.direction;
			iso.walkable = obj.walkable;
			iso.clickEnabled = clickEnable;
			iso.floorWidth = obj.size * SceneConst.GRID_SIZE;
			iso.floorHeight = obj.size * SceneConst.GRID_SIZE;
			isoWorld.addToWorld(iso);
			return iso;
		}
		
		/**
		 *	添加城门到场景中 
		 * @param isoData
		 * @param dataObj
		 * @param isoPosition 要添加的位置
		 * @return 城门部件列表
		 * 
		 */
		private function addGateToWorld(isoData:IsoDataObj,dataObj:BuildingObj,isoPosition:IsoPosition):Array
		{
			//获取城门排列方向
			var $keyNum:int = int(isoData.serverId.charAt(isoData.serverId.length-2)) % 2;
			var $direction:String = $keyNum == 0 ? "left" : "right";
			var $isoList:Array = [];
			var $pos:IsoPosition = isoPosition;
			var $gatePart:BuildingIsoObject;
			
			for (var i:int = 1; i <= 4; i++) 
			{
				var $gateIsoData:IsoDataObj = isoData.clone();
				$gateIsoData.partId = i;
				$gatePart = new BuildingIsoObject($gateIsoData,dataObj);
				if($direction == "left")
				{
					$gatePart.x3d = ($pos.x + (i - 1) *$gateIsoData.size)*SceneConst.GRID_SIZE;
					$gatePart.z3d = $pos.z*SceneConst.GRID_SIZE;
					
				}else{
					$gatePart.x3d = $pos.x*SceneConst.GRID_SIZE;
					$gatePart.z3d = ($pos.z + (i - 1)*$gateIsoData.size)*SceneConst.GRID_SIZE;
				}
				$isoList.push($gatePart);
			}
			for (var j:int = 0; j < $isoList.length; j++) 
			{
				$gatePart = $isoList[j];
				$gatePart.parts = $isoList;
				isoWorld.addToWorld($gatePart);
			}
			return $isoList;
		}

		protected function onMapChange(event:IsoWorldEvent):void
		{
			var sceneIndexList:Array = event.data as Array;
			var matsList:Array = [];
			for (var i:int = 0; i < sceneIndexList.length; i++) 
			{
				var sceneX:int = sceneIndexList[i][0];
				var sceneZ:int = sceneIndexList[i][1];
				var posX:int = SceneConst.CENTER_BLOCK_X + sceneX;
				var posZ:int = SceneConst.CENTER_BLOCK_Z + sceneZ;
				var key:String = posX + "_" + posZ;
				if(_sceneStaticDic[key] == null)
				{
					var resKey:ResKey = new ResKey(key,"",DllItem.TYPE_JSON);
					matsList.push(resKey); 
//					trace("请求地图数据：(",sceneX + "," + sceneZ,")");
				}
			}
			cleanUpScene();
//			isoWorld.update9SceneGrid();
			Dll.getInstance().getMatResList(matsList,onMapListComp,Priority.LOW,DllItem.TYPE_JSON);
		}
		
		private function onMapListComp(dataArr:Array):void
		{
			_waitingMapDataList = _waitingMapDataList.concat(dataArr);
		}
		
		/**
		 *	检查地图数据等待处理列表中是否有未处理的数据，有则添加相应地图快 
		 * @param event
		 * 
		 */
		protected function checkWaitingMapHandler(event:TimerEvent):void
		{
			if(_waitingMapDataList.length > 0)
			{
				var mapRes:ResKey = _waitingMapDataList.shift();
				var key:String = mapRes.key;
				var mapData:Object = mapRes.data;
				if(_sceneStaticDic[key] == null && mapData != null)
				{
					_sceneStaticDic[key] = mapData;
					var offsetArr:Array = String(key).split("_");
					var sX:int = (uint(offsetArr[0]) - SceneConst.CENTER_BLOCK_X );
					var sZ:int = ( uint(offsetArr[1]) - SceneConst.CENTER_BLOCK_Z);
					var offsetX:int = uint(offsetArr[0]) * SceneConst.X_NUM;
					var offsetZ:int =uint(offsetArr[1]) * SceneConst.Z_NUM;
					if(mapData)
					{
						addObjectsByMapData(mapData,offsetX,offsetZ);
					}
//					trace("注册地图数据:(",sX + "," + sZ,")");
					isoWorld.registerSceneFlag(sX,sZ);
					updateMapGrid();
				}
			}
		}
		
		private function cleanUpScene():void
		{
			var scenes:Array = isoWorld.current9SceneArr;
			var sceneIndex:Object = {};
			//建立索引
			for (var i:int = 0; i < scenes.length; i++) 
			{
				var sX:int = scenes[i][0];
				var sZ:int = scenes[i][1];
				sceneIndex[sX + "_" + sZ] = true;
			}
			
			for(var mapPos:String in _sceneStaticDic) 
			{
				var offsetArr:Array = mapPos.split("_");
				sX = (uint(offsetArr[0]) - SceneConst.CENTER_BLOCK_X );
				sZ = ( uint(offsetArr[1]) - SceneConst.CENTER_BLOCK_Z);
				if(sceneIndex[sX + "_" + sZ] == null)//如果非当前9屏
				{
					//注销
					isoWorld.removeIsoObjectFormScene(sX,sZ);
					isoWorld.removeSceneFlag(sX,sZ);
					delete _sceneStaticDic[mapPos];
				}
			}
			
			//清理字典们
			var dicList:Array = [_territoryDic,_buildingDic,_eIdIsoDic];//要清理的iso字典列表
			var iso:JusticeIsoObject;
			var key:String;
			for (var j:int = 0; j < dicList.length; j++) 
			{
				var dic:Dictionary = dicList[j];
				for(key in dic) 
				{
					iso = dic[key] as JusticeIsoObject;
					if(iso.disposed)
					{
						delete dic[key];
					}
				}
			}
			
		}
		
		/**
		 *	根据serverId返回对应类型的场景物件的类
		 * @param serverId
		 * @return 
		 * 
		 */
		private function serverIdToIsoClass(serverId:String):Class
		{
			var type:String = ServerIdUtil.idToType(serverId);
			var retClass:Class;
			switch(type)
			{
				case TypeConst.TYPE_FLOOR:
				{
					retClass =  FloorIsoObject;
					break;
				}
				case TypeConst.TYPE_TERRITORY:
				{
					retClass = TerritoryIsoObject;
					break;
				}
				case TypeConst.TYPE_COLLECTION:
				{
					retClass = CollectionIsoObject;
					break;
				}
				case TypeConst.TYPE_BUILDING:
				{
					retClass = BuildingIsoObject;
					break;
				}
				case TypeConst.TYPE_TROOP:
				{
					retClass = TroopIsoObject;
					break;
				}
				case TypeConst.TYPE_DECORATION:
				{
					retClass = DecorationIsoObject;
					break;
				}
				default:
				{
					break;
				}
			}
			return retClass;
		}
		
		private function moveTroop(troop:TroopIsoObject,newPath:Boolean = false):void
		{
//			TweenLite.killTweensOf(troop);
			var currentP3d:Point3D = new Point3D(troop.x3d,troop.y3d,troop.z3d);
			var playerPos:Object = _walkManager.goNextStep(troop.troopId);
			if(playerPos.moveEnd == false)
			{
				var targetPos:IsoPosition = getIsoPostionInScene(playerPos.x,playerPos.y);
				troop.direction = IsoUtils.targetDirection(currentP3d,new Point3D(targetPos.x,0,targetPos.z)) +270 -22.5;
				var dist:int = Point.distance(new Point(currentP3d.x,currentP3d.z),new Point(targetPos.x,targetPos.z));
				var duration:Number;
				if(newPath && dist > SceneConst.ONE_STEP_DISTANCE)
				{
					duration = 0;
				}else{
					duration = 1/troop.speed*dist*0.05;
				}
				TweenLite.to(troop,duration,{x3d:targetPos.x,z3d:targetPos.z,useFrames:false,ease:Linear.easeNone,onUpdate:updateGridFun,onUpdateParams:[troop],onComplete:moveTroop,onCompleteParams:[troop]});
			}
			function updateGridFun(iso:TroopIsoObject):void
			{
				isoWorld.moveGrid(iso,iso.postion3D);
			}
		}
		
		/**
		 *	定位到某个领地的主城 
		 * @param territoryObj 领地的IsoDataObj
		 * @param tween 是否使用缓动动画,false时将直接切换到指定点
		 */
		private function locatedToTerritory(territoryObj:TerritoryIsoDataObj,tween:Boolean = true):void
		{
			var $territoryPos:Point3D = territoryObj.postion3D;
			var $centerPos:Point3D = new Point3D(
				$territoryPos.x + 16*SceneConst.GRID_SIZE,
				0,
				$territoryPos.z + 10*SceneConst.GRID_SIZE);//偏移到领地中心
			locatedToPosition3d($centerPos,tween);
		}
		
		/**
		 *	将镜头定位到指定的isoObject物件中心
		 * @param iso
		 * @param tween 是否使用缓动动画,false时将直接切换到指定点
		 */
		private function locatedToIso(iso:JusticeIsoObject,tween:Boolean = true):void
		{
			if(iso == null){return};
			var rollPoint:Point;
			if(iso)
			{
				var point3D:Point3D = new Point3D(iso.middleX, 0, iso.middleZ);
				locatedToPosition3d(point3D,tween);
			}
		}
		
		/**
		 *	将镜头定位到场景上的某一点 
		 * @param position3d
		 * @param tween 是否使用缓动动画,false时将直接切换到指定点
		 */
		private function locatedToPosition3d(position3d:Point3D,tween:Boolean = true):void
		{
			var rollPoint:Point;
			rollPoint = IsoUtils.isoToScreen(position3d);
			rollPoint.x += isoWorld.contentX;
			rollPoint.y += isoWorld.contentY;
			if(rollPoint)
			{
				var a:Number = isoWorld.contentX;
				var b:Number = isoWorld.contentY;
				var $offsetX:Number = App.appStage.stageWidth / 2 - rollPoint.x;
				var $offsetY:Number = App.appStage.stageHeight / 2 - rollPoint.y;
				if(tween)
				{
					TweenLite.to(isoWorld, 0.8, {contentX:a + $offsetX,contentY:b + $offsetY});
				}else{
					isoWorld.contentX = a + $offsetX;
					isoWorld.contentY = b + $offsetY;
				}
			}
		}
		
		/**
		 *	更新静态地图数据 (只有9屏场景变化时才会更新)
		 * @param enforce 是否强制更新
		 * 
		 */
		private function updateMapGrid(enforce:Boolean = false):void
		{
			var sceneArr:Array = isoWorld.current9SceneArr;
			var registerBlock:Array = sceneArr[0];//注册点块 
			var dxNum:int = 0;
			var dzNum:int = 0;
			var changed:Boolean = false;
			if(_currentRegisterBlock == null)
			{
				changed = true;
			}
			else if(_currentRegisterBlock[0] != registerBlock[0] || _currentRegisterBlock[1] != registerBlock[1])
			{
				var dx:int = _currentRegisterBlock[0] - registerBlock[0] ;
				var dz:int = _currentRegisterBlock[1] - registerBlock[1] ;
				dxNum = dx * SceneConst.X_NUM;
				dzNum = dz * SceneConst.Z_NUM;
				changed = true;
			}
			if(changed || enforce)
			{
				_currentRegisterBlock = registerBlock;
				_walkManager.updateMapGrid(isoWorld.getMapGrid(),dxNum,dzNum);
			}
		}
		
		
		/**
		 *	根据iso的在场景中的位置(基于格子)换算出当前应该在mapGrid地图数据中的位置
		 * @param isoPosition
		 * @return 
		 * 
		 */
		private function getPositionInMapGrid(isoPosition:IsoPosition):IsoPosition
		{
			var sceneArr:Array = isoWorld.current9SceneArr;
			var registerBlock:Array = sceneArr[0];//注册点块
			
			var x:int = isoPosition.x - registerBlock[0] * SceneConst.X_NUM;
			var z:int = isoPosition.z - registerBlock[1] * SceneConst.Z_NUM;
			return new IsoPosition(x,z);
		}
		
		/**
		 *	 根据mapGrid地图数据中的位置换算出当前iso应该在的在场景中的位置(基于格子)
		 * @param mapGridX
		 * @param mapGridY
		 * @return 
		 * 
		 */
		private function getScenePosition(mapGridX:int,mapGridY:int):IsoPosition
		{
			var sceneArr:Array = isoWorld.current9SceneArr;
			var registerBlock:Array = sceneArr[0];//注册点块
			var x:int = (mapGridX + registerBlock[0] * SceneConst.X_NUM);
			var z:int = (mapGridY + registerBlock[1] * SceneConst.Z_NUM);
			return new IsoPosition(x,z);
		}
		
		/**
		 *	根据mapGrid地图数据中的位置换算出在场景中应当处于的位置
		 * @param x 地图数据中的位置x
		 * @param y 地图数据中的位置y
		 * @return 
		 * 
		 */
		private function getIsoPostionInScene(x:int,y:int):IsoPosition
		{
			var sceneArr:Array = isoWorld.current9SceneArr;
			var registerBlock:Array = sceneArr[0];//注册点块
			var registerX:int = registerBlock[0];
			var registerZ:int = registerBlock[1];
			var xNum:int = SceneConst.X_NUM;
			var zNum:int = SceneConst.Z_NUM;
			var x3d:int = (x + registerX * xNum) * SceneConst.GRID_SIZE;
			var z3d:int = (y + registerZ * zNum) * SceneConst.GRID_SIZE;
			return new IsoPosition(x3d,z3d);
		}
		
		/**
		 *	 将walkManager产生的相对于自身寻路地图的路径转化为世界绝对坐标路径
		 * @param path
		 * @return 
		 * 
		 */
		private function gridPathToAbsPath(path:Array):Array
		{
			var absPath:Array = [];
			for (var i:int = 0; i < path.length; i++) 
			{
				var scenePos:IsoPosition = getIsoPostionInScene(path[i].x,path[i].y);
				var absPos:IsoPosition = SceneUtil.relPosToAbsPos(scenePos.x,scenePos.z);
				absPath.push({"x":absPos.x,"y":absPos.z});
			}
			return absPath;
		}
		
		/**
		 *	 将世界绝对坐标路径转化为walkManager可识别的相对于自身寻路地图的路径
		 * 	@param absPath
		 * 	@return 
		 * 
		 */
		private function absPathToGridPath(absPath:Array):Array
		{
			var gridPath:Array = [];
			for (var i:int = 0; i < absPath.length; i++) 
			{
				var scenePos:IsoPosition = SceneUtil.absPosToRelPos(absPath[i].x,absPath.y);
				var gridPos:IsoPosition = getPositionInMapGrid(scenePos);
				gridPath.push({"x":gridPos.x,"y":gridPos.z});
			}
			return gridPath;
		}
		
		private function onFogTimer(e:TimerEvent = null):void
		{
			updateFogContent();
		}
		
		/**
		 *	刷新迷雾偏移
		 * 
		 */
		private function updateFogContent():void
		{
//			var t:Number = getTimer();
			_fogManager.updateContextXY(isoWorld.contentX,isoWorld.contentY);
//			trace(getTimer() - t);
		}
		
		public function getGrid(size:int = 1):MapGrid
		{
			if(_walkManager)	return _walkManager.getGrid(size);
			return null;
		}
		
		
		/**
		 *	刷新领地网格状态 
		 * 
		 */
		private function updateTerritoryGrid():void
		{
			if(userTerritoryIso!=null)
			{
				if(actionType == ActionType.NORMAL)
				{
					if(userTerritoryIso)userTerritoryIso.hideRangeGrid();
				}else{
					if(userTerritoryIso)userTerritoryIso.showRangeGrid();
				}
			}
		}
		
		/**
		 *	更新场景各物件的拼接关系 
		 * 
		 */
		private function updateCombo():void
		{
			//先处理之前连接过节点的拼接
			while(_comboLinkedList.length>0)
			{
				updateSingleCombo(_comboLinkedList.pop(),0,false);
			}
			if(dragItemList && dragItemList.length>0)
			{
				updateSingleCombo(dragItemList[0]);
			}
		}
		
		private var _comboLinkedList:Array = [];//自动拼接时连接过的节点
		/**
		 *	更新传入单个iso及其周围地板的拼接属性，会不断向四周蔓延检查 
		 * @param iso
		 * @param depth 蔓延深度
		 * @param remenberLink 是否记录连接节点
		 */
		private function updateSingleCombo(iso:JusticeIsoObject,depth:int = 1,remenberLink:Boolean = true):void
		{
			if(iso.isCombo)//如果对象需要自动拼接
			{
				var $pos:IsoPosition = iso.isoPosition;
				var $size:int = iso.isoDataObj.size;
				var $up:Array =  isoWorld.getObjectListByXZ($pos.x,$pos.z-$size);
				var $right:Array =  isoWorld.getObjectListByXZ($pos.x-$size,$pos.z);
				var $down:Array =  isoWorld.getObjectListByXZ($pos.x,$pos.z+$size);
				var $left:Array =  isoWorld.getObjectListByXZ($pos.x+$size,$pos.z);
				var $checkList:Array = [$right,$up,$left,$down];
				var $comboRim:String = "";
				for (var i:int = 0; i < $checkList.length; i++) 
				{
					var $arr:Array = $checkList[i];
					if($arr.length > 0)
					{
						var $has:Boolean = false;
						for (var j:int = 0; j < $arr.length; j++) 
						{
							if(($arr[j] as JusticeIsoObject).isoDataObj.serverId == iso.isoDataObj.serverId)
							{
								$comboRim += "1";
								$has = true;
								if(remenberLink)
								{
									_comboLinkedList.push($arr[j]);
								}
								if(depth>0)
								{
									updateSingleCombo($arr[j],depth-1,remenberLink);
								}
								break;
							}
						}
						if($has==false)$comboRim += "0";
					}else{
						$comboRim += "0";
					}
				}
				iso.comboRim = $comboRim;
			}
		}
		
		private function get dragItemList():Array
		{
			return _dragItemList;
		}
		
		/**
		 *	 场景当前吸附在鼠标上被拖动的物件列表
		 * @param value
		 * 
		 */
		private function set dragItemList(list:Array):void
		{
			var $item:JusticeIsoObject;
			if(_dragItemList)
			{
				for (var i:int = 0; i < _dragItemList.length; i++) 
				{
					$item = _dragItemList[i];
					if($item)
					{
						$item.filter = null;
					}
				}
			}
			_dragItemList = list;
			if(_dragItemList == null || _dragItemList.length == 0)return;
			for (var j:int = 0; j < _dragItemList.length; j++) 
			{
				$item = _dragItemList[j];
				if($item)
				{
					$item.filter =  new GradientGlowFilter(0,0,[0x8AD964,0x8AD964],[0,1],[0,255],0,0,0.3,1,"inner",false);
				}
			}
		}
		
		public function get actionType():String
		{
			return _actionType;
		}
		
		/**
		 *	 场景当前行动模式(状态)
		 * @param value
		 * 
		 */
		public function set actionType(value:String):void
		{
			if(_actionType == value)return;
			_actionType = value;
			switch (value)
			{
				case ActionType.BUILD:
					
					break;
				case ActionType.REMOVE:
					
					break;
				case ActionType.MOVE:
					
					break;
				case ActionType.MOVETOBAG:
					
					break;
				case ActionType.NORMAL:
					break;
			}
			updateTerritoryGrid();

			
			var cmd:SceneCommand = new SceneCommand(SceneCommand.SCENE_CMD_ACTIONTYPE_CHANGED);
			cmd.actionType = value;
			cmd.data = value;
			dispatch(cmd);
		}

		
		private function get userTerritoryIso():TerritoryIsoObject
		{
			if(_modelData.userTerritoryObj)
			{
				var $terrtoryObj:TerritoryIsoDataObj = _modelData.userTerritoryObj;
				var $key:String = $terrtoryObj.absX + "_" +$terrtoryObj.absZ;
				if(_territoryDic[$key])
				{
					return _territoryDic[$key] as TerritoryIsoObject;
				}
			}
			return null;
		}
		
		protected function onResize(event:Event):void
		{
			if(isoWorld != null)
			{
				isoWorld.width = App.appStage.stageWidth;
				isoWorld.height = App.appStage.stageHeight;
			}
		}
		
		private function get isoWorld():JusticeIsoWorld
		{
			return _sceneView.isoWorld as JusticeIsoWorld;
		}


	}
}